
<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { FormInstance, FormRules,ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { getApi, postApi,searchData } from '@/axios/http.js'
import {setLocalStorageWithExpiry , getLocalStorageWithExpiry} from '../stor/index.js'
import {useTokenStore} from '../stor/token.js'

import {useRouter} from 'vue-router'
//路由导航
const router = useRouter();
//from表单
const ruleFormRef = ref<FormInstance>()

//定义参数集
const ruleForm = ref({
  username: 'wangzhang',
  password: '123abc456ef',
  rePassword: '',
})

//校验用户名
const validateUsername = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('请输入用户名'))
  }
  setTimeout(() => {
      if ( !(8 <= value.length  &&  value.length <= 16) ) {
        callback(new Error('用户名长度为8~16字符'))
      } else {
        callback()
      }
    
  }, 1000)
}

//校验密码
const validatePass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  }else if(!(8 <= value.length  &&  value.length <= 16)){
    callback(new Error('密码长度为8~16字符'))
  } else {
    if (ruleForm.value.rePassword !== '') {
      if (!ruleFormRef.value) return
      ruleFormRef.value.validateField('rePassword')
    }
    callback()
  }
}
//校验确认密码
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入确认密码'))
  }else if(!(8 <= value.length  &&  value.length <= 16)){
    callback(new Error('密码长度为8~16字符'))
  } else if (value !== ruleForm.value.password) {
    callback(new Error("两次密码不匹配"))
  } else {
    callback()
  }
}


//校验规则
const rules = reactive<FormRules<typeof ruleForm>>({
    username: [{ validator: validateUsername, trigger: 'blur' }],
    password: [{ validator: validatePass, trigger: 'blur' }],
    rePassword: [{ validator: validatePass2, trigger: 'blur' }],
})
//注册提交
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      //使用URLSearchParams进行参数传递
      const params = new URLSearchParams();
      for(let key in ruleForm.value){
        params.append(key,ruleForm.value[key]);
      }
     postApi("/user/register",params,null)
      .then((res: any)=>{
        const statusCode = res.code; 
        if(0===statusCode){
          ElMessage.success("注册成功")
        }
      }).catch((error:any)=>{
        ElMessage.error("请求失败");
      });
      
    } else {
      ElMessage.error("请输入数据");
    }
  })
}

const tokenStore = useTokenStore();
//登录
const login =  (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      //使用URLSearchParams进行参数传递
      const params = new URLSearchParams();
      for(let key in ruleForm.value){
        params.append(key,ruleForm.value[key]);
      }
    const headcontenttype='application/x-www-form-urlencoded'
    postApi('user/login',params,headcontenttype)
    .then((res: any)=>{
      const statusCode = res.code; 
        if(0===statusCode){
          const token = res.data
         // setLocalStorageWithExpiry("token",token);   
         //使用pinia存储token     
          tokenStore.setToken(token);                
          ElMessage.success("登录成功")
          //登录成功后，路由到首页
          router.push('/');

        }
    })
    } else {
      ElMessage.error("请输入数据");
    }
  })
}


//重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
//显示注册还是登录
const isRegister= ref(false);

</script>

<template>
    <el-row class="login-page">
     <el-col :span="12" class="bg"></el-col>  
     <el-col :span="6" :offset="3" class="form">
         <!--注册-->
    <el-form ref="ruleFormRef"  :model="ruleForm"  :rules="rules" label-width="80px"
              v-if="isRegister">
        <el-form-item >
        <h1>注册</h1>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
        <el-input :prefix-icon="User" v-model="ruleForm.username" type="text" autocomplete="off" />
      </el-form-item>
        <el-form-item label="密码" prop="password">
        <el-input  :prefix-icon="Lock" v-model="ruleForm.password" type="password" autocomplete="off" />
      </el-form-item>
      <el-form-item label="确认密码" prop="rePassword">
        <el-input :prefix-icon="Lock" v-model="ruleForm.rePassword"  type="password"  autocomplete="off"/>
      </el-form-item>
      <el-form-item>
        <el-button  class="button" type="primary" auto-insert-space @click="submitForm(ruleFormRef)">
          注册
        </el-button>
      </el-form-item>
      <el-form-item class="flex">
        <el-link type="info" :underline="false" @click="isRegister = false;resetForm(ruleFormRef)">◀返回</el-link>
      </el-form-item>
    </el-form>
    <!--登录-->
    <el-form ref="ruleFormRef" :model="ruleForm"  :rules="rules" label-width="80px"  v-else>
        <el-form-item >
        <h1>登录</h1>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
        <el-input :prefix-icon="User" v-model="ruleForm.username" type="text" autocomplete="off" />
      </el-form-item>
        <el-form-item label="密码" prop="password">
        <el-input :prefix-icon="Lock" v-model="ruleForm.password" type="password" autocomplete="off" />
      </el-form-item>
      <el-form-item class="flex">
        <div class="flex">
            <el-checkbox>记住我</el-checkbox>
            <el-link type="primary" :underline="false">忘记密码</el-link>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="button" auto-insert-space @click="login(ruleFormRef)">
          登录
        </el-button>
      </el-form-item>
      <el-form-item class="flex">
        <el-link type="info" :underline="false" @click="isRegister = true; resetForm(ruleFormRef)">注册 -></el-link>
      </el-form-item>
    </el-form>
</el-col> 
</el-row>
  </template>
<style lang="scss" scoped>
 /* 样式 */
.login-page {
    height: 100vh;
    background-color: #fff;

    .bg {
       
        background: url('@/assets/auto1.png') no-repeat center / cover;
        border-radius: 0 15px 15px 0;
    }

    .form {
        display: flex;
        flex-direction: column;
        justify-content: center;
        user-select: none;

        .title {
            margin: 0 auto;
        }

        .button {
            width: 100%;
        }

        .flex {
            width: 100%;
            display: flex;
            justify-content: space-between;
        }
    }
}
</style>
    